<template>
  <div class="shortcuts">
    <div class="flex flex-col gap-2">
      <!-- 快捷键开关控制 -->
      <div class="flex items-center gap-2">
        <div>{{ $t("setup.shortcutInfo.shortcutControl") }}</div>
        <div>
          <el-switch
            v-model="shortcutControl"
            class="jtyj-switch"
            @change="handleChangeSwitch"
          >
          </el-switch>
        </div>
        <div class="flex items-center ml-auto">
          <el-button
            class="jtyj-button-text"
            type="text"
            icon="el-icon-refresh-left"
            >{{ $t("setup.shortcutInfo.shortcutRestore") }}</el-button
          >
        </div>
      </div>
      <!-- 快捷键冲突 -->
      <div class="flex items-center gap-2">
        <div class="flex items-center gap-1">
          <div>{{ $t("setup.shortcutInfo.shortcutConflict") }}</div>
          <span role="img" class="mx-1 opacity-25 appIcon">
            <el-popover
              popper-class="common-popover"
              placement="top"
              title="当快捷键发生冲突时，智能训练与验证子系统 优先占用。"
              trigger="hover"
            >
              <svg-icon
                slot="reference"
                icon-class="explain"
                width="14"
                height="14"
              />
            </el-popover>
          </span>
        </div>
        <el-select v-model="priority" placeholder="请选择" class="jtyj-select">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <!-- 输入框搜索 -->
      <el-input
        prefix-icon="el-icon-search"
        v-model="shortcutQuery"
        placeholder="搜索快捷键"
        class="jtyj-input"
        clearable
        @change="handleChangeQuery"
      ></el-input>
      <div class="flex flex-col">
        <div
          v-for="(item, index) in getHeaderList()"
          :key="item.name"
          v-show="item.show"
        >
          <div class="flex flex-col gap-3">
            <div class="shortcut-title">
              {{ item.name }}
            </div>
            <div class="flex flex-col gap-3">
              <div
                v-for="subItem in getHeaderMenuList(item)"
                :key="subItem.nameEn"
                class="flex px-3"
                :data-action="subItem.nameEn"
                v-show="item.show"
              >
                <div class="flex-1" style="color: #475467">
                  {{ subItem.name }}
                </div>
                <div class="flex flex-col gap-2 items-end">
                  <template v-if="!Array.isArray(subItem.shortcut_way)">
                    <div class="flex gap-2 items-center">
                      <div class="flex items-center gap-2">
                        <el-input
                          placeholder="点击设置快捷键"
                          v-model="shortcutsValue[subItem.nameEn]"
                          :disabled="subItem.disabled || disabledAll"
                          class="jtyj-input no-caret"
                          clearable
                          @focus="handleFocus($event, subItem)"
                          @blur="handleBlur"
                          @clear="handleChangeShortcuts($event, subItem)"
                        ></el-input>
                        <span role="img" class="opacity-0 appIcon">
                          <svg-icon
                            slot="reference"
                            icon-class="refresh"
                            width="14"
                            height="14"
                            @click="handleReset(subItem)"
                          />
                        </span>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div
                      v-for="(ele, index) in subItem.shortcut_way"
                      class="flex gap-2 items-center"
                      :key="ele"
                    >
                      <span v-if="index == 1" style="color: #475467">或</span>
                      <div class="flex items-center gap-2">
                        <el-input
                          placeholder="点击设置快捷键"
                          v-model="shortcutsValue[subItem.nameEn][index]"
                          :disabled="subItem.disabled || disabledAll"
                          class="jtyj-input no-caret"
                          clearable
                          @focus="handleFocus($event, subItem)"
                          @blur="handleBlur"
                          @clear="handleChangeShortcuts($event, subItem)"
                        ></el-input>
                        <span role="img" class="opacity-0 appIcon">
                          <svg-icon
                            slot="reference"
                            icon-class="refresh"
                            width="14"
                            height="14"
                            @click="handleReset(subItem)"
                          />
                        </span>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
          <el-divider
            v-if="item.title && index != getHeaderList().length - 1"
            class="jtyj-divider"
          ></el-divider>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isValidShortcuts } from "@/utils/tools/index";
import { mapState } from "vuex";
import Mousetrap from "mousetrap";
export default {
  data() {
    return {
      currentShortcut: null, // 当前正在编辑的快捷键
      priority: null, // 优先级
      shortcutQuery: null,
      shortcutControl: true, // 控制键盘快捷键开启关闭，默认开启
      disabledAll: false, // 禁用所有快捷键
      isEditShortcut: false, // 是否正在编辑快捷键
      shortcutsValue: {}, // 快捷键的启用方式
      shortcutsData: [], // 快捷键数据
      options: [
        {
          label: "智能训练与验证子系统优先",
          value: "jtyj",
          id: "jtyjFirst",
        },
        {
          label: "浏览器优先",
          value: "browser",
          id: "browserFirst",
        },
      ],
    };
  },
  computed: {
    ...mapState({
      shortcutsList: (state) => state.systemStyle.shortcutsList,
    }),
  },
  created() {
    this.shortcutsData = JSON.parse(JSON.stringify(this.shortcutsList));
    this.initShortcuts();
    // switchToEnglish();
    // function switchToEnglish() {
    //   // 模拟按下Control和空格键来切换输入法（在某些系统上有效）
    //   document.dispatchEvent(
    //     new KeyboardEvent("keydown", { key: "Space", ctrlKey: true })
    //   );
    //   document.dispatchEvent(
    //     new KeyboardEvent("keyup", { key: "Space", ctrlKey: true })
    //   );
    // }
  },
  mounted() {
    window.addEventListener("keydown", this.handleKeydown);
  },
  beforeDestroy() {
    window.removeEventListener("keydown", this.handleKeydown);
  },
  methods: {
    // 初始化快捷键数据
    initShortcuts() {
      this.shortcutsData.forEach((element) => {
        if (!element.title && !this.shortcutsValue[element.nameEn]) {
          this.$set(this.shortcutsValue, element.nameEn, element.shortcut_way);
        }
      });
    },
    // 获取快捷键标题数据
    getHeaderList() {
      return this.shortcutsData.filter((item) => item.title && item.show);
    },
    // 获取每个标题下快捷键菜单项数据
    getHeaderMenuList(header) {
      return this.shortcutsData.filter(
        (item) => item.flag == header.flag && item.show && !item.title
      );
    },
    // 当快捷键开关状态发生变化后
    handleChangeSwitch(val) {
      this.disabledAll = !val;
    },
    // 输入框聚焦
    handleFocus(e, subItem) {
      this.isEditShortcut = this.disabledAll ? false : true;
      this.currentShortcut = subItem;
      //   e.target.blur(); // 移除焦点
    },
    // 输入框失去焦点
    handleBlur(e) {},
    // 快捷键的启用方式发生变化时
    handleChangeShortcuts(val, subItem) {
      this.shortcutsValue[subItem.nameEn] = "";
    },
    // 当筛选的内容发生变化后
    handleChangeQuery(val) {
      this.shortcutsData = JSON.parse(JSON.stringify(this.shortcutsList));
      const ele = this.shortcutsData.filter(
        (item) => item.name.includes(val) && !item.title
      );
      if (ele.length == 0) return;
      this.shortcutsData.forEach((subItem) => {
        if (ele.filter((ele) => ele.nameEn == subItem.nameEn).length != 0) {
          this.$set(subItem, "show", true);
        } else if (
          ele.filter((ele) => ele.flag == subItem.flag).length != 0 &&
          subItem.title
        ) {
          this.$set(subItem, "show", true);
        } else {
          this.$set(subItem, "show", false);
        }
      });
    },
    // 重置快捷键的启用方式
    handleReset(subItem) {
      const val = this.shortcutsList.filter(
        (item) => item.nameEn == subItem.nameEn
      )[0].shortcut_way;
      this.shortcutsValue[subItem.nameEn] = val;
    },
    // 处理键盘事件
    handleKeydown(event) {
      if (this.disabledAll || !this.isEditShortcut) return; // 如果所有快捷键被禁用，或者当前没有在编辑快捷键的启用方式，则不处理键盘事件
      const key = event.key; // 键的内容
      const code = event.keyCode; // 键值
      if (code == 8 || code == 46) {
        // 点击删除或者Del键时，直接清空
        this.shortcutsValue[this.currentShortcut.nameEn] = "";
      }
      if (
        event.altKey == true ||
        event.ctrlKey == true ||
        event.shiftKey == true
      ) {
        let str =
          event.altKey && event.ctrlKey && event.shiftKey
            ? "Alt + Ctrl + Shift"
            : event.altKey && event.ctrlKey
            ? "Alt + Ctrl"
            : event.altKey && event.shiftKey
            ? "Alt + Shift"
            : event.ctrlKey && event.shiftKey
            ? "Ctrl + Shift"
            : event.altKey
            ? "Alt"
            : event.ctrlKey
            ? "Ctrl"
            : "Shift";
        if (isValidShortcuts(event).flag) {
          this.shortcutsValue[this.currentShortcut.nameEn] =
            str + " + " + isValidShortcuts(event).str;
        } else {
          this.shortcutsValue[this.currentShortcut.nameEn] = str;
        }
      } else {
        if (isValidShortcuts(event).flag) {
          this.shortcutsValue[this.currentShortcut.nameEn] =
            isValidShortcuts(event).str;
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.shortcuts {
  width: 100%;
  height: 100%;
  .shortcut-title {
    color: var(--app-header-text-color-hover);
  }
}
</style>